package my.graduation.interceptor;

import io.jsonwebtoken.Claims;
import my.graduation.constant.JwtClaimsConstant;
import my.graduation.context.BaseContext;
import my.graduation.properties.JwtProperties;
import my.graduation.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: RavenLyn
 * @Date: 2024-11-28
 *
 * jwt令牌校验拦截器
 */

@Component
public class JwtPatientInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 1 从请求头中获取令牌
        String authorization = request.getHeader(jwtProperties.getPatientTokenName());
        // 2 校验令牌是否存在于redis黑名单中
        Boolean isBlack = redisTemplate.hasKey(authorization);
        if(isBlack){
            return false;
        }
        // 2 校验令牌
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getPatientSecretKey(), authorization);
            Integer patientId = Integer.valueOf(claims.get(JwtClaimsConstant.PATIENT_ID).toString());
            BaseContext.setCurrentId(patientId);
//            System.out.println(BaseContext.getCurrentId());
            // 3 通过，放行
            return true;
        }catch (Exception e){
            // 4 不通过，返回错误响应
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
